package com.gp.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gp.mapper.GoodsMapper;
import com.gp.pojo.Goods;
import com.gp.service.GoodsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    private static RestHighLevelClient client;


    static {
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost("192.168.200.129", 9200, "http"));
        client = new RestHighLevelClient(restClientBuilder);
    }

    /**
     * 创建索引库goods
     * @return
     * @throws IOException
     */
    @Override
    public String bulkAdd() throws IOException {
        //a.创建CreateIndexRequest对象，并指定索引库名称
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("goods");
        //b.指定settings配置
        createIndexRequest.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 1)
                .put("index.max_result_window", 100000)
        );
        //c.指定mapping配置
        createIndexRequest.mapping(
                "\n" +
                        "{\n" +
                        "    \"properties\": {\n" +
                        "      \"id\": {\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      },\n" +
                        "      \"name\":{\n" +
                        "        \"type\": \"text\",\n" +
                        "        \"analyzer\": \"ik_max_word\"\n" +
                        "      },\n" +
                        "      \"price\":{\n" +
                        "        \"type\": \"integer\"\n" +
                        "      },\n" +
                        "      \"num\":{\n" +
                        "        \"type\": \"integer\"\n" +
                        "      },\n" +
                        "      \"image\":{\n" +
                        "        \"type\": \"keyword\",\n" +
                        "        \"index\":\"false\"\n" +
                        "      },\n" +
                        "      \"images\":{\n" +
                        "        \"type\": \"keyword\",\n" +
                        "        \"index\":\"false\"\n" +
                        "      },\n" +
                        "      \"createTime\":{\n" +
                        "        \"type\": \"date\"\n" +
                        "      },\n" +
                        "      \"categoryId\":{\n" +
                        "        \"type\": \"integer\"\n" +
                        "      },\n" +
                        "      \"categoryName\":{\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      },\n" +
                        "      \"brandName\":{\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      }\n" +
                        "    }\n" +
                        "}", XContentType.JSON
        );
        //d.发起请求，得到响应
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.isAcknowledged());

        List<Goods> goodsList = this.list();
        //b. 创建BulkRequest对象
        BulkRequest bulkRequest = new BulkRequest();
        //c. 创建多个IndexRequest对象，组织文档数据，并添加到BulkRequest中
        for (Goods good : goodsList) {
            IndexRequest request = new IndexRequest("goods");
            request.id(good.getId());
            String jsonString = JSON.toJSONString(good);
            bulkRequest.add(request.source(jsonString, XContentType.JSON));
        }
        //4. 发起请求
        BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(responses.status());
        return responses.status().toString();
    }

    /**
     * 查询
     * @return
     * @throws IOException
     */
    @Override
    public List<Goods> findAll() throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(
                QueryBuilders.matchAllQuery()
        )
                .trackTotalHits(true);//设置显示总数 解除显示10000条限制
        SearchRequest request = new SearchRequest("goods");
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        long total = response.getHits().getTotalHits().value;
        System.out.println("totalShards = " + total);
        SearchHit[] hits = response.getHits().getHits();
        List<Goods> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            list.add(JSON.parseObject(hit.getSourceAsString(), Goods.class));
        }
        return list;
    }


    @After
    public void close(){
        if(client !=null){
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
